package cn.dankal.flyaudio;

import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.jeremyliao.liveeventbus.LiveEventBus;

import androidx.lifecycle.Observer;
import api.ShopUserServiceFactory;
import api.UserServiceFactory;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.base.fragment.BaseFragment;
import cn.dankal.basiclib.common.bus.LiveDataBusConstants;
import cn.dankal.basiclib.domain.HttpStatusCode;
import cn.dankal.basiclib.exception.LocalException;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.pojo.UserInfoBean;
import cn.dankal.basiclib.pojo.UserScoresEntity;
import cn.dankal.basiclib.rx.AbstractSubscriber;
import cn.dankal.basiclib.util.SharePreferenceManager;
import cn.dankal.basiclib.util.TimeUtil;
import cn.dankal.basiclib.util.image.PicUtils;
import cn.dankal.flyaudio.configs.OrderPagerConfigs;
import cn.dankal.flyaudio.configs.TestData;
import cn.dankal.flyaudio.dialog.PersonalSignSuccessDialog;
import cn.dankal.flyaudio.personal.AddressManagerActivity;
import cn.dankal.flyaudio.personal.InviteFriendsActivity;
import cn.dankal.flyaudio.personal.MyActivityActivity;
import cn.dankal.flyaudio.personal.MyCardActivity;
import cn.dankal.flyaudio.personal.MyCollectionActivity;
import cn.dankal.flyaudio.personal.MyCurrentActivity;
import cn.dankal.flyaudio.personal.MyOrderActivity;
import cn.dankal.flyaudio.personal.PersonalProfileActivity;
import cn.dankal.flyaudio.personal.RefundActivity;
import cn.dankal.flyaudio.personal.ScoreRecordActivity;
import cn.dankal.flyaudio.personal.SignInActivity;
import cn.dankal.flyaudio.personal.driverlisense.DriverLisenseActivity;
import cn.dankal.flyaudio.personal.setting.SettingActivity;
import io.reactivex.disposables.Disposable;

public class NewPersonalFragment extends BaseFragment implements View.OnClickListener {

    private TextView signView;

    private View carAuthorizeView;

    private ImageView settingView;

    private TextView identifyView;

    private ImageView avatarView;

    private TextView scoreView;

    private TextView nickName;

    private TextView flowerNumView;

    private TextView fansNumView;

    private TextView collectionNumView;

    private TextView currentNumView;
    private boolean isHead = false;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_personal_2;
    }

    @Override
    protected void initComponents() {
        signView = getView().findViewById(R.id.tv_sign);
        signView.setOnClickListener(this);
        carAuthorizeView = getView().findViewById(R.id.cl_car_authorize);
        carAuthorizeView.setOnClickListener(this);
        settingView = getView().findViewById(R.id.iv_setting);
        settingView.setOnClickListener(this);
        flowerNumView = getView().findViewById(R.id.tv_flower_num);
        fansNumView = getView().findViewById(R.id.tv_fans_num);
        collectionNumView = getView().findViewById(R.id.tv_collection_num);
        currentNumView = getView().findViewById(R.id.tv_current_num);
        identifyView = getView().findViewById(R.id.tv_identify);
        scoreView = getView().findViewById(R.id.tv_score);
        avatarView = getView().findViewById(R.id.iv_avatar);
        nickName = getView().findViewById(R.id.tv_nickname);
        getView().findViewById(R.id.iv_qrcode).setOnClickListener(this);
        getView().findViewById(R.id.tv_all).setOnClickListener(this);
        getView().findViewById(R.id.ll_payment).setOnClickListener(this);
        getView().findViewById(R.id.ll_send_store).setOnClickListener(this);
        getView().findViewById(R.id.ll_collection_store).setOnClickListener(this);
        getView().findViewById(R.id.ll_evaluate).setOnClickListener(this);
        getView().findViewById(R.id.tv_score).setOnClickListener(this);
        getView().findViewById(R.id.cl_my_activity).setOnClickListener(this);
        getView().findViewById(R.id.cl_my_address).setOnClickListener(this);
        getView().findViewById(R.id.ll_refund).setOnClickListener(this);
        getView().findViewById(R.id.iv_avatar).setOnClickListener(this);
        getView().findViewById(R.id.ll_collection_list).setOnClickListener(this);
        getView().findViewById(R.id.ll_flower_list).setOnClickListener(this);
        getView().findViewById(R.id.cl_my_coupon).setOnClickListener(this);
        getView().findViewById(R.id.ll_this).setOnClickListener(this);

//        getView().findViewById(R.id.cl_change_account).setOnClickListener(this);
//        getView().findViewById(R.id.cl_change_account1).setOnClickListener(this);
//        getView().findViewById(R.id.cl_change_account2).setOnClickListener(this);
        getUserInfo();
        fetchUserScores();
        LiveEventBus.get(LiveDataBusConstants.REFRESH_USER_SCORES, String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                scoreView.setText("总积分 " + DKUserManager.getUserScores().getUsable());
            }
        });
        LiveEventBus.get("update_user_info", String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                getUserInfo();
            }
        });
    }

    private void getUserInfo() {
        if (DKUserManager.isLogined()) {
            UserInfoBean userInfoBean = DKUserManager.getUserInfo();
            scoreView.setText("总积分 " + DKUserManager.getUserScores().getUsable());
            identifyView.setText(userInfoBean.isTourist() ? "游客" : "会员");
            nickName.setText(userInfoBean.getName());
            if (!isHead) {
                PicUtils.loadAvatar(userInfoBean.getAvatar(), avatarView);
            }
            flowerNumView.setText(0 + "");
            fansNumView.setText(0 + "");
            collectionNumView.setText(userInfoBean.getUserFavoriteCount());
            currentNumView.setText(userInfoBean.getUserInformationCount());
            UserServiceFactory.user_info()
                    .subscribe(new AbstractSubscriber<UserInfoBean>(this) {
                        @Override
                        public void onNext(UserInfoBean userInfoBean) {
                            DKUserManager.updateUserInfo(userInfoBean);
                            identifyView.setText(userInfoBean.isTourist() ? "游客" : "会员");
                            nickName.setText(userInfoBean.getName());
//                            if (!isHead) {
//                                PicUtils.loadAvatar(userInfoBean.getAvatar(), avatarView);
//                            }
                            flowerNumView.setText(0 + "");
                            fansNumView.setText(0 + "");
                            collectionNumView.setText(userInfoBean.getUserFavoriteCount());
                            currentNumView.setText(userInfoBean.getUserInformationCount());

//                            swipe_toload_layout.isRefreshing = false;
//                            isCreate = false
//                            isHasLoadOnce = true
//                            isLoding = false
                        }
                    });
        }
    }

    public void fetchUserScores(){
        ShopUserServiceFactory.userScores().subscribe(new io.reactivex.Observer<BaseResponse<UserScoresEntity>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse<UserScoresEntity> userScoresEntityBaseResponse) {
                DKUserManager.updateUserInfoScores(userScoresEntityBaseResponse.getData());
                scoreView.setText("总积分 " + DKUserManager.getUserScores().getUsable());
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof LocalException) {
                    LocalException exception = (LocalException) e;
                    //401 重新获取access token , 如果还返回412 就是refresh token 也失效了。需要重新登录
                    if (exception.getErrorCode() == HttpStatusCode.TOKEN_INVAILD||
                            exception.getErrorCode() == HttpStatusCode.UNAUTHORIZED) {
                        //view.showToast("登录信息失效");
                    } else {
                    }
                } else {
                    Log.e("SubscriberThrowable", e.getMessage());
                }
            }

            @Override
            public void onComplete() {

            }
        });
    }

    private void isSign() {
        ShopUserServiceFactory.isSginIn()
                .subscribe(new AbstractSubscriber<BaseResponse<Boolean>>(this) {
                    @Override
                    public void onNext(BaseResponse<Boolean> booleanBaseResponse) {
                        if (booleanBaseResponse.getData()) {
                            doSign();
//                            startActivity(new Intent(getContext(), SignInActivity.class));
                        } else {
                            doSign();
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (R.id.tv_sign == id) {
            isSign();
        } else if (R.id.cl_my_activity == id) {
            startActivity(new Intent(getContext(), MyActivityActivity.class));
        } else if (R.id.cl_car_authorize == id) {
            startActivity(new Intent(getActivity(), DriverLisenseActivity.class));
        } else if (R.id.iv_setting == id) {
            startActivity(new Intent(getContext(), SettingActivity.class));
        } else if (R.id.tv_all == id) {
            Intent intent = new Intent(getContext(), MyOrderActivity.class);
            intent.putExtra("order_type", OrderPagerConfigs.PAGE_TYPE_ALL);
            startActivity(intent);
        } else if (R.id.ll_payment == id) {
            Intent intent = new Intent(getContext(), MyOrderActivity.class);
            intent.putExtra("order_type", OrderPagerConfigs.PAGE_TYPE_PAYMENT);
            startActivity(intent);
        } else if (R.id.ll_send_store == id) {
            Intent intent = new Intent(getContext(), MyOrderActivity.class);
            intent.putExtra("order_type", OrderPagerConfigs.PAGE_TYPE_SEND_STORE);
            startActivity(intent);
        } else if (R.id.ll_collection_store == id) {
            Intent intent = new Intent(getContext(), MyOrderActivity.class);
            intent.putExtra("order_type", OrderPagerConfigs.PAGE_TYPE_COLLECTION_STORE);
            startActivity(intent);
        } else if (R.id.ll_evaluate == id) {
            Intent intent = new Intent(getContext(), MyOrderActivity.class);
            intent.putExtra("order_type", OrderPagerConfigs.PAGE_TYPE_EVALUATE);
            startActivity(intent);
        } else if (R.id.ll_refund == id) {
            Intent intent = new Intent(getContext(), RefundActivity.class);
            startActivity(intent);
        } else if (R.id.tv_score == id) {
            Intent intent = new Intent(getContext(), ScoreRecordActivity.class);
            startActivity(intent);
        } else if (R.id.cl_my_address == id) {
            startActivity(new Intent(getContext(), AddressManagerActivity.class));
        } else if (R.id.iv_avatar == id) {
            startActivity(new Intent(getContext(), PersonalProfileActivity.class));
        } else if (R.id.ll_collection_list == id) {
            startActivity(new Intent(getContext(), MyCollectionActivity.class));
        } else if (R.id.cl_my_coupon == id) {
            startActivity(new Intent(getContext(), MyCardActivity.class));
        } else if (R.id.ll_flower_list == id) {
//            startActivity();
        } else if (R.id.ll_this == id) {
            startActivity(new Intent(getContext(), MyCurrentActivity.class));
        } else if (R.id.iv_qrcode == id) {
            startActivity(new Intent(getContext(), InviteFriendsActivity.class));
        }
//        else if (R.id.cl_change_account == id) {
//            ToastUtils.showShort("切换成功，请退出重新进入");
        SharePreferenceManager.setCurrentUser(TestData.USE_USER1);
//            TestData.setUser(TestData.USE_USER1);
//        } else if (R.id.cl_change_account1 == id) {
//            ToastUtils.showShort("切换成功，请退出重新进入");
//            SharePreferenceManager.setCurrentUser(TestData.USE_USER2);
//            TestData.setUser(TestData.USE_USER2);
//        } else if (R.id.cl_change_account2 == id) {
//            ToastUtils.showShort("切换成功，请退出重新进入");
//            SharePreferenceManager.setCurrentUser(TestData.USE_USER3);
//            TestData.setUser(TestData.USE_USER3);
//        }
    }

    private void doSign() {
        ShopUserServiceFactory.doSignIn().subscribe(new AbstractSubscriber<BaseResponse<Object>>(this) {
            @Override
            public void onNext(BaseResponse<Object> objectBaseResponse) {
                SharePreferenceManager.setCachedIsSign(TimeUtil.getDateYMD1(System.currentTimeMillis()),
                        true);
                DKUserManager.fetchUserScores();
                PersonalSignSuccessDialog dialog = new PersonalSignSuccessDialog();
                dialog.setOnCloseListener(new PersonalSignSuccessDialog.OnCloseListener() {
                    @Override
                    public void onClose() {
                        startActivity(new Intent(getContext(), SignInActivity.class));
                    }
                });
                dialog.show(getChildFragmentManager(), "");
            }
        });
    }
}
